<template>
  <div class="app-container">
    <div style="font-size:20px; margin-bottom: 50px;">
      <span>请刷卡入闸</span>
      <el-divider></el-divider>
    </div>
    <el-row :gutter="30">
      <!-- 身份证信息 -->
      <el-col :span="12"> 
        <el-card  v-bind:class="{ 'box-card': true, 'noActive': isReadIdCard }">
          <div slot="header" class="clearfix">
            <span>身份证信息</span>
          </div>
          <el-form ref="form" :model="form" label-width="120px">
            <el-form-item label="姓名">
              <el-input v-model="form.name" disabled></el-input>
            </el-form-item>

            <el-form-item label="身份证号码">
              <el-input v-model="form.idCard" disabled></el-input>
            </el-form-item>

            <!-- 未扫描证时不显示 -->
            <el-form-item v-show="!isReadIdCard">
              <el-alert 
                v-if="readStatus.id"
                title="身份证读入成功"
                type="success"
                show-icon
              > 
              </el-alert>

              <el-alert
                v-if="!readStatus.id"
                title="身份证读入失败"
                type="error"
                show-icon
              >
              </el-alert>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12"> 
        <!-- 运通卡信息 -->
        <el-card  v-bind:class="{ 'box-card': true, 'noActive': isReadIcCard }">
          <div slot="header" class="clearfix">
            <span>PCC卡信息</span>
          </div>
           <el-form ref="form" :model="form" label-width="120px">
            <el-form-item label="PCC卡号">
              <el-input v-model="form.permitNo" disabled></el-input>
            </el-form-item>

            <!-- <el-form-item label="认证号">
              <el-input v-model="form.permitNo" disabled></el-input>
            </el-form-item> -->

            <!-- 未扫描证时不显示 -->
            <el-form-item v-show="!isReadIcCard">
              <el-alert
                v-if="readStatus.pcc"
                title="PCC卡读入成功"
                type="success"
                show-icon
              >
              </el-alert>

              <el-alert
                v-if="!readStatus.pcc"
                title="PCC卡读入失败"
                type="error"
                show-icon
              >
              </el-alert>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
 
    <el-row> 
      <el-col :span="24" style="text-align: center; padding: 20px; "> 
        <h3> 
          {{ showMessage.msg }}  
        </h3>
      </el-col>
    </el-row>

    
    <el-dialog :title="dialogObj.title" :visible.sync="dialogObj.alertVisible">
      <span>{{dialogObj.msg}}</span>

       <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogObj.alertVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div> 
</template>

<script>
import axios from 'axios'
import {
  showSuccessMsg,
  showErrorMsg,
  showWarningMsg,
  showInfoMsg,
  showNotify,
  debugLog,
  log,
} from '@/utils/message'
import { ipcRenderer } from 'electron'
import Tinymce from '@/components/Tinymce'
export default {
  components: { Tinymce },
  data() {
    return {
      pauseReadIdCardThread: null,
      pauseReadIcCardThread: null,
      countdownThread: null,
      sendMqttMsgSeq: 0,
      readPauseTime: 10000,
      readIdCardThread: null,
      readIdCardThread: null,
      pauseReadCardThread: null,
      appConfigData: null,
      showMessage: {  
        msg: '请刷卡......',
        success: false,
        type: 'success',
      },
      isReadIdCard: true,
      isReadIcCard: true,
      dialogObj: {
        alertVisible: false, 
        title: '*操作系统连接有问题!',
        msg: 'msg'
      },
      readStatus: {
        pc: false,
        id: false
      },
      form: {
        pccId: '',
        name: '', 
        idCard: '',
        permitNo: ''
      },
    }
  },
  created() {
    /*
    log(__filename)
    log(__dirname) */
    setTimeout(() => {
      this.startMqttConnect()
    }, 2000)

    // TODO 在这里启动读卡线程 根据类型加载指定的读卡器
    setTimeout(() => {
      //  加载dll
      // this.loadCardDll()
      this.initReadThread()
    }, 6000)

    /**
     * TODO 这里需要一个handle 处理各种异常信息提示 和服务器返回值
     *
     */
  }, 
  methods: {
    // 开启读ID卡线程
    startReadIdCardThread() {
      this.stopReadIdCardThread()
      this.readIdCardThread = window.setInterval(() => {
        if (this.isReadIdCard) {
          ipcRenderer.send('read-id-card')
        }
      }, 1000)
    },
    //关闭读ID卡线程
    stopReadIdCardThread() {
      if (this.readIdCardThread) {
        window.clearInterval(this.readIdCardThread)
      }
      return true
    },
    // 开启读IC卡线程
    startReadIcCardThread() {
      this.stopReadIcCardThread()
      debugLog('开始读 read-ic-card', '读卡信息')
      this.readIcCardThread = window.setInterval(() => {
        if (this.isReadIcCard) {
          ipcRenderer.send('read-ic-card')
        }
      }, 1000)
    },
    //关闭读IC卡线程
    stopReadIcCardThread() {
      if (this.readIcCardThread) {
        window.clearInterval(this.readIcCardThread)
      }
      return true
    },
    // 暂停读身份证
    pauseReadIdCard() {
      this.isReadIdCard = false
      //清空倒计时
      this.clearCountdownThread()
      // 读卡成功后暂停  如果ic卡的状态也是暂停说明就可以提交了
      if (this.isReadIcCard) {
        this.readCardCountdown('请刷PCC卡')
      } else {
        this.showMsg('服务器正在验证卡信息', 'info')
        this.sendMqttMessage()
      }
    },
    pauseReadIcCard() {
      this.isReadIcCard = false
      //清空倒计时
      this.clearCountdownThread()

      if (this.isReadIdCard) {
        this.readCardCountdown('请刷身份证')
      } else {
        this.showMsg('服务器正在验证卡信息', 'info')
        this.sendMqttMessage()
      }
    },
    readCardCountdown(msg) {
      var count = 10
      this.clearCountdownThread()

      this.countdownThread = window.setInterval(() => {
        count--
        this.showMsg(
          msg + '......      超时倒计时 : ' + count + ' sec.',
          'info'
        )
        if (count <= 1) {
          this.timeoutHandle()
        }
      }, 1000)
    },
    clearCountdownThread() {
      if (this.countdownThread) {
        window.clearInterval(this.countdownThread)
      }
    },
    timeoutHandle() {
      this.clearCountdownThread()
      this.showMsg('处理超时...', 'warning')
      setTimeout(() => {
        this.resetReadThread()
      }, 1000)
    },
    //初始化读卡服务
    initReadThread() {
      this.stopReadThread()
      debugLog('初始化读卡服务', '读卡信息')
      //重启服务
      setTimeout(() => {
        this.loadCardDll()
      }, 2000)
    },
    resetReadThread() {
      //关闭暂停程序
      if (this.pauseReadIdCardThread) {
        window.clearTimeout(this.pauseReadIdCardThread)
      }
      if (this.pauseReadIcCardThread) {
        window.clearTimeout(this.pauseReadIcCardThread)
      }

      window.setTimeout(() => {
        this.isReadIdCard = true
        this.isReadIcCard = true
        this.resetShowMessage()
        this.resetFormObject()
        debugLog('恢复读卡服务')
      }, 10000)
    },
    //清空暂停线程
    stopReadThread() {
      //关闭暂停程序
      if (this.pauseReadIdCardThread) {
        window.clearTimeout(this.pauseReadIdCardThread)
      }
      if (this.pauseReadIcCardThread) {
        window.clearTimeout(this.pauseReadIcCardThread)
      }
      //停止读卡线程
      this.stopReadIdCardThread()
      this.stopReadIcCardThread()
      this.isReadIdCard = true
      this.isReadIcCard = true
      this.resetShowMessage()
      debugLog('关闭读卡服务')
      //重启服务
      /*     setTimeout(() => {
        this.loadCardDll()
      }, 2000) */
    },
    // 重置
    resetShowMessage() {
      log('=== resetShowMessage ===')
      this.showMessage = {
        msg: '请刷卡......',
        success: false,
        type: 'success',
      }
    },
    //  =====start===读卡操作=====
    // 初始化加载dll
    loadCardDll() {
      console.log('=loadCardDll')
      ipcRenderer.send('load-card-dll-thread')
      ipcRenderer.on('load-card-dll-thread-reply', (event, res) => {
        log('load-card-dll-thread-reply')
        debugLog(res)
        this.registerReadListener()
        this.startReadIdCardThread()
        this.startReadIcCardThread()

        debugLog('读卡服务启动成功')
      })
    },
    // 注册ID和IC卡消息监听器
    registerReadListener() {
      // 注册ID卡消息监听器
      ipcRenderer.on('read-id-card-reply', (event, res) => {
        // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码  111
        if (this.isReadIdCard) {
          log('====read-id-card-reply====')
          log(res)
          let msgInfo = JSON.stringify(res)
          if (res.readCode === 0) {
            // 读卡成功
            debugLog('身份证读取成功', 'success')
            this.form.name = res.name
            this.form.idNo = res.idNo
            this.showMsg('身份证读取成功', 'success')
            //暂停读取ID卡线程
            window.setTimeout(() => {
              this.pauseReadIdCard()
            }, 1000)
            msgInfo += '====读卡成功'
          } else if (res.readCode === 2) {
            // this.showMsg('身份证无效', 'error')
            msgInfo += '====身份证无效'
          } else {
            log('身份证设备连接错误', 'warning')
            msgInfo += '====身份证设备连接错误'
            // this.showMsg('身份证设备连接错误', 'warning')
          }
          debugLog(msgInfo, '读卡信息')
        }
      })
      // 注册IC卡消息监听器
      ipcRenderer.on('read-ic-card-reply', (event, res) => {
        log('====read-ic-card-reply====')
        let msgInfo = JSON.stringify(res)
        log(msgInfo)
        if (res.readCode == 0) {
          this.form.pccId = res.cardNo
          this.form.permitNo = res.permitNo
          this.showMsg('PCC卡读取成功', 'success')
          window.setTimeout(() => {
            this.pauseReadIcCard()
          }, 1000)

          log('====PCC卡读取成功')
        } else if (res.readCode === 2) {
          log('PPC无效', 'error')
        } else {
          log('PC卡设备端口连接错误', 'warning')
        }
      })
    },
    // =====end===读卡操作=====
    // =====start===MQTT=====
    deviceAuthenticate(queryObject) {
      log(queryObject)
      debugLog(queryObject.eipUr)
      axios
        .post(queryObject.eipUrl + '/api/deviceAuthenticate', queryObject, {
          timeout: 3000,
        })
        .then((res) => {
          // var resObj = JSON.parse(res)
          var ret = res.data
          log(ret)
          if (ret.result && ret.result === 'success') {
            log('===设备注册成功===')
            this.$message({
                message: '设备注册成功',
                type: 'success'
            })
            debugLog(ret, '设备注册')
            this.appConfigData.sessionId = ret.data.sessionId
            this.appConfigData.serviceInstanceIpAddress =
              ret.data.serviceInstanceIpAddress
            this.appConfigData.serviceInstanceMqttPort =
              ret.data.serviceInstanceMqttPort
            this.connectMqtt(this.appConfigData)
          } else {
            showErrorMsg(res)
          }
        })
        .catch((error) => {
          showErrorMsg(error)
        })
    },
    // 启动 MQTT服务器连接
    startMqttConnect() {
      this.closeMqttConnect()
      if (!this.appConfigData) {
        this.readAppConfig()
      }

      if (this.appConfigData) {
        setTimeout(() => {
          log('========appConfigData========')
          log(this.appConfigData)
          this.deviceAuthenticate(this.appConfigData)
          // var appConfigInfo = JSON.parse(this.appConfigDat)
          //验证读取本地配置文件  每次都
          // this.connectMqtt(this.appConfigData)
        }, 2000)
      }
    },
    connectMqtt(mqttObject) {
      log('startMqttConnect')
      debugLog(mqttObject, 'MQTT连接信息')
      ipcRenderer.send('start-mqtt-connect', mqttObject)

      ipcRenderer.on('start-mqtt-connect-reply', (event, res) => {
        log('====start-mqtt-connect-reply====')
        debugLog(res, 'MQTT链接结果')
      })
      //注册业务返回监听器
      ipcRenderer.on('send-mqtt-client-message-reply', (event, res) => {
        log('===send-mqtt-client-message-reply===')
        if ('客户端未连接' === res){ 
          this.startMqttConnect()
        }
        debugLog(res)
      })

      ipcRenderer.on('mqtt-server-message-topic', (event, res) => {
        log('===mqtt-server-message-topic===')
        log(res)
        this.handleMqttMessage(res)
      })
    },
    // 关闭 MQTT服务器
    closeMqttConnect() {
      log('closeMqttConnect')
      ipcRenderer.send('close-mqtt-connect')

      ipcRenderer.on('close-mqtt-connect-reply', (event, res) => {
        log('close-mqtt-connect-reply')
        log(res)
      })
    },
    // 发送MQTT消息
    sendMqttMessage() {
      this.sendMqttMsgSeq += 1
      let message = {
        dt: {
          idInfo: {
            idNu: this.form.idNo ,
            name: this.form.name ,
          },
          nGenFullTractorNo: '',
          tcCode: this.form.permitNo ,
          ip: getNetworkIp(),
          cardId: this.form.pccId ,
        },
        ic: 'Auto', 
        sn: this.appConfigData.deviceSerialNo ,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      debugLog(message, '请求MQTT信息')
      ipcRenderer.send('send-mqtt-client-message', 'api/auto',message)
    },
    // MQTT后端业务返回消息处理方法
    handleMqttMessage(mqttMessage) {
      //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":1,"dt":["192764","zxc","","y|GD|BW8337|",""]}

      if (mqttMessage) {
        var messageObject = JSON.parse(mqttMessage)
        debugLog(messageObject, '回传信息')
        if (messageObject.rc && messageObject.rc == 1) {
          this.showMsg('刷卡操作成功', 'success')
        } else if (messageObject.rc === 3015) {
          this.showMsg('该车在港区逗留超过一小时, 请联络闸口服务台! ', 'warning')
          this.dialogObj.alertVisible = true
          this.dialogObj.title = '*操作系统连接有问题！'
          this.dialogObj.msg = messageObject.rm
        
        } else if (messageObject.rc) {
          //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":26,"rm":"未知的读卡器错误"}
          this.showMsg(messageObject.rm, 'warning')
        } else {
          this.showMsg('未知错误，请联系管理员。', 'warning')
        }
        this.resetReadThread()
      }
    },
    // =====end===MQTT=====

    // =====start===注册业务，也是测试用=====
    readAppConfig() {
      ipcRenderer.send('read-app-config', '读取本地文件的配置文件')
      ipcRenderer.on('read-app-config-reply', (event, res) => {
        log(res)
        this.appConfigData = JSON.parse(res.data)
        this.startMqttConnect()
      })
    },
    showMsg(msg, type) {
      this.showMessage.msg = msg
      this.showMessage.type = type
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

.noActive { 
   filter:alpha(opacity=40);  /*设置透明度为60%*/
   opacity:0.4;  /*非IE浏览器下设置透明度为60%*/
}
</style>
 